package com.superyee.commonlib.widgets;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;

import com.superyee.commonlib.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class IndexView extends View {


    private OnItemClickListener mOnItemClickListener;
    private List<String> mLetters;
//	String[] b = { "★", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K",
//			"L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X",
//			"Y", "Z", "#"};

    int choose = 0, textSize = 20;
    Paint paint = new Paint();
    boolean showBkg = false, showPosition = false;
    private PopupWindow mPopupWindow;
    private Handler handler = new Handler();
    public static String z_xing = "*";//"★";
    public static String z_jing = "#";
    private int textColor;
    private Float[] letterPosition;
    private Bitmap starBitmap;
    private ViewPager mViewPager;
    private int offset = 0;

    public IndexView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    public IndexView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public IndexView(Context context) {
        super(context);
        init();
    }

    private void init() {
        textColor = getResources().getColor(R.color.list_content_title);
        textSize = getResources().getDimensionPixelSize(R.dimen.dp_16);
        mLetters = new ArrayList<String>();
        for (char i = 'A'; i <= 'Z'; i++) {
            mLetters.add(Character.toString(i));
        }
        mLetters.add(z_jing);
//        mLetters.add(0, z_xing);

        letterPosition = new Float[mLetters.size()];
//        createBitmap();
    }

    public void setParentViewPager(ViewPager viewPager) {
        this.mViewPager = viewPager;
    }

    public void setOffsetHeight(int offset) {
        this.offset = offset;
    }

    /**
     * 控制是否显示星号
     *
     * @param showFavorite
     */
    public void showFavorite(boolean showFavorite) {
        if (!showFavorite) {
            mLetters.remove(z_xing);
        } else if (!mLetters.contains(z_xing)) {
            mLetters.add(0, z_xing);
        }
        letterPosition = new Float[mLetters.size()];
        invalidate();
    }

    /**
     * 指定字母列选中的位置
     *
     * @param selection
     */
    public void setSelection(int selection) {
        this.choose = selection;
        invalidate();
    }

    public void setSelection(String pinyin) {
        for (int i = 0; i < mLetters.size(); i++) {
            if (mLetters.get(i).equals(pinyin)) {
                this.choose = i;
                break;
            }
        }
        invalidate();
    }

    private void createBitmap() {
        Bitmap bit = BitmapFactory.decodeResource(getResources(), R.drawable.comm_icon_back);
        float postScale = textSize * 1.0f / bit.getWidth();
        Matrix matrix = new Matrix();
        matrix.postScale(postScale, postScale);
        starBitmap = Bitmap.createBitmap(bit, 0, 0, bit.getWidth(), bit.getHeight(), matrix, true);
    }

    private float viewHeight;

    public void resetHeight() {
        float height = 0;
        if (mViewPager != null) {
            Rect rect = new Rect();
            mViewPager.getGlobalVisibleRect(rect);
            height = rect.bottom - rect.top;
            height -= (getPaddingBottom() + getPaddingTop());
        } else {
            height = getHeight() - getPaddingTop() - getPaddingBottom();
        }
        height -= offset;
        if (height == viewHeight) {
            return;
        } else {
            invalidate();
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
//		if (showBkg) {
//			canvas.drawColor(Color.parseColor("#00000000"));
//		}
        if (mViewPager != null) {
            Rect rect = new Rect();
            mViewPager.getGlobalVisibleRect(rect);
            viewHeight = rect.bottom - rect.top;
            viewHeight -= (getPaddingBottom() + getPaddingTop());
        } else {
            viewHeight = getHeight() - getPaddingTop() - getPaddingBottom();
        }
        viewHeight -= offset;
        int width = getWidth();
        float singleHeight = viewHeight / mLetters.size();
        for (int i = 0; i < mLetters.size(); i++) {
            paint.setColor(textColor);
            paint.setTypeface(Typeface.DEFAULT);
            paint.setFakeBoldText(true);
            paint.setTextSize(getResources().getDimension(R.dimen.dp_14));
            paint.setAntiAlias(true);
//			float xPos = width / 2 - paint.measureText(b[i]) / 2;
//			float yPos = singleHeight * i + singleHeight;
            float xPos = (width - paint.measureText(mLetters.get(i))) / 2;
            float yPos = singleHeight * i + singleHeight + getPaddingTop();// - (paint.getFontSpacing() - textSize);

            if (i == choose && showPosition) {
                paint.setColor(Color.WHITE);

                Paint bgPaint = new Paint(paint);
                bgPaint.setColor(ContextCompat.getColor(getContext(), R.color.colorAccent));
//				Rect ate_bg = new Rect(0, (int)(yPos - textSize), width, (int)(yPos + (paint.getFontSpacing()-textSize + 2)));
                Rect bg = new Rect(0, (int) (yPos - singleHeight), width, (int) (yPos));
//				Rect ate_bg = new Rect(0, (int)(yPos - paint.measureText(b[i]) - textSize/2), width, (int)(yPos + textSize/2));
                canvas.drawRect(bg, bgPaint);
            }
//            if (mLetters.get(i).equals(z_xing)) {
//                canvas.drawBitmap(starBitmap, (width - textSize) / 2, yPos - singleHeight + (singleHeight - textSize) / 2, null);
//            } else
            {
//				canvas.drawText(b[i], xPos, yPos, paint);
                canvas.drawText(mLetters.get(i), xPos, yPos - (singleHeight - textSize) / 2 - (paint.getFontSpacing() - textSize) / 2, paint);
            }
            paint.reset();

            letterPosition[i] = yPos - singleHeight;
        }

    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        final int action = event.getAction();
        final float y = event.getY();
//		final int c = (int)((y - getPaddingTop())/((getHeight() - getPaddingTop() - getPaddingBottom())/mLetters.size()));
        int c = 0;
        try {
            c = Arrays.binarySearch(letterPosition, (y - getPaddingTop()));
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (c < 0) {
            c = -c - 2;
        }
        switch (action) {
            case MotionEvent.ACTION_DOWN:
                showBkg = true;
//			if (oldChoose != c) 
            {
                if (c >= 0 && c < mLetters.size()) {
                    if (performItemClicked(c)) {
                        choose = c;
                        invalidate();
                    }
                }
            }

            break;
            case MotionEvent.ACTION_MOVE:
//			if (oldChoose != c) 
            {
                if (c >= 0 && c < mLetters.size()) {
                    if (performItemClicked(c)) {
                        choose = c;
                        invalidate();
                    }
                }
            }
            break;
            case MotionEvent.ACTION_UP:
                showBkg = false;
//			choose = -1;
                dismissPopup();
                invalidate();
                break;
            default:
                dismissPopup();
//			choose = -1;
                invalidate();
        }

        return true;
    }

    TextView popText;

    private void showPopup(int item) {
        if (mPopupWindow == null) {
            handler.removeCallbacks(dismissRunnable);
//			mPopupText = new TextView(getContext());
//			mPopupText.setBackgroundColor(Color.GRAY);
//			mPopupText.setTextColor(Color.CYAN);
//			mPopupText.setTextSize(getResources().getDimension(R.dimen.text_size_24));
//			mPopupText.setGravity(Gravity.CENTER);
            View popView = LayoutInflater.from(getContext()).inflate(R.layout.comm_pop_text_view, null);
            popText = (TextView) popView.findViewById(R.id.textView);
            mPopupWindow = new PopupWindow(popView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        }

        String text = mLetters.get(item);
        popText.setText(text);
        if (mPopupWindow.isShowing()) {
            mPopupWindow.update();
        } else {
            mPopupWindow.showAtLocation(getRootView(),
                    Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL, 0, 0);
        }
    }

    private void dismissPopup() {
        handler.postDelayed(dismissRunnable, 500);
    }

    Runnable dismissRunnable = new Runnable() {

        @Override
        public void run() {
            if (mPopupWindow != null) {
                mPopupWindow.dismiss();
            }
        }
    };


    protected void onDetachedFromWindow() {
        if (mPopupWindow != null) {
            mPopupWindow.dismiss();
        }
        super.onDetachedFromWindow();
    }

    public void setOnItemClickListener(OnItemClickListener listener) {
        mOnItemClickListener = listener;
    }

    private boolean performItemClicked(int item) {
        boolean result = false;
        if (mOnItemClickListener != null) {
            result = mOnItemClickListener.onItemClick(mLetters.get(item));
            showPopup(item);
        }
        return result;
    }

    public interface OnItemClickListener {
        boolean onItemClick(String s);
    }

}
